package com.k2data.app.k2bq.siem.utils;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import com.k2data.app.k2bq.siem.request.RequestConf;

import java.io.IOException;

public class OkHttpUtils {

    public static Response send(OkHttpClient client, RequestConf rc) throws IOException {
        if ("GET".equals(rc.getMethod())) {
            return sendGet(client, rc);
        } else {
            return sendPost(client, rc);
        }
    }

    private static Response sendGet(OkHttpClient client, RequestConf rc) throws IOException {
        String url = rc.getUrl();
        Headers headers = Headers.of(rc.getHeaders());

        Request request = new Request.Builder().url(url).headers(headers).build();
        return client.newCall(request).execute();
    }

    private static Response sendPost(OkHttpClient client, RequestConf rc) throws IOException {
        String url = rc.getUrl();
        Headers headers = Headers.of(rc.getHeaders());
        String json = (rc.getBody() == null || rc.getBody().size() == 0) ? rc.getBodyStr() : JSON.toJSONString(rc.getBody());

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder().url(url).headers(headers).post(body).build();
        return client.newCall(request).execute();
    }

}
